#pragma once

#include <iostream>
#include <functional>
#include "Protocol.hpp"
#include "Connection.hpp"
#include "NetCal.hpp"

class PackageParse
{
public:
    void Excute(Connection *con)
    {
        while (1)
        {
            // 2.报文解析，提取有效载荷
            std::string package = Decode(con->Inbuffer());
            if (package.empty())
                break; // 读取完毕，跳出循环
            std::cout << "------------------" << std::endl;
            std::cout << "package: \n"
                      << package << std::endl;

            // 3.提取到有效载荷，反序列化
            auto req = Factor::BuildRequest();
            req->Deserialize(package);

            // 4.业务处理，输入请求，得到应答
            // auto resp = _process(req);
            auto resp = cal.Calculator(req);

            // 5.序列化应答
            std::string respJson;
            resp->Serialize(&respJson);
            std::cout << "respJson: \n"
                      << respJson << std::endl;

            // 6.添加报头
            respJson = Encode(respJson);
            std::cout << "respjson add header done: \n"
                      << respJson << std::endl;

            // 7.将数据添加到发送缓冲区
            con->AppendOutbuffer(respJson);
        }
        // 到这里，数据处理完毕得到应答数据，可以将发送缓冲区的数据进行发送了
        if (!con->Outbuffer().empty())
            con->_handler_sender(con);
    }

private:
    NetCal cal;
};